package com.flong.juc.charter1;

import org.junit.Test;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author:liangjl
 * @Date: 2020/3/29-19:26
 * @Eamil:jilongliang@sina.com
 * @Description:
 */
public class SaleTicket {
    /**
     * 主线程入口
     *  public static void main(String[] args)
     */

    @Test
    public  void test1() throws Exception {
        final Ticket ticket = new Ticket();

       /* new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 40; i++) {
                    ticket.sale();
                }     
            }
        },"A").start();*/

        new Thread(() -> { for (int i = 0; i < 40; i++)  {ticket.sale();}},"A").start();
        new Thread(() -> { for (int i = 0; i < 40; i++)  {ticket.sale();}},"B").start();
        new Thread(() -> { for (int i = 0; i < 40; i++)  {ticket.sale();}},"C").start();
    }
}


/**
 * synchronized  重量鎖
 */
class Ticket {
    //三十張票
    private int number = 30;
    //公平鎖
    Lock lock = new ReentrantLock();

    public void sale() {
        lock.lock();
        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "\t卖出第：" + (number--) + "\t还剩下：" + number);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            //釋放鎖
            lock.unlock();
        }
    }
}